
// Serial protocol handling....
//
// 'packets' are of the form:
//
// byte 1 - syncronization byte (10101010), as start-of-packet.
// byte 2 - command byte, denotes operation to be done
// byte 3 - data byte, parameter for command.
// byte 4 - checksum byte

#include <avr/io.h>
#include <avr/interrupt.h>
//#include <avr/eeprom.h>
//#include "common.h"
#include "serial.h"

//RXC ISR variables                                                             
uint8_t r_index;		// current packet byte index
uint8_t r_buffer[RX_PACKET_SIZE];	// input packet
uint8_t r_ready;		//flag for receive done
uint8_t r_char;		//current character  
uint8_t r_state;	//current character  

//ISR(USART_RXC_vect) __attribute__ ((naked));
ISR(USART_RX_vect) { 
	r_char=UDR;    //get a char
	//UDR=r_char;    //then print it (echo, we won't be for now...)`
	//build the input string

	if(r_state == RX_STATE_SYNC && r_char == 0xaa) {
		r_state = RX_STATE_RCV;
	} else if(r_state == RX_STATE_RCV) {
		r_buffer[r_index]=r_char;
		r_index++;
		if (r_index == RX_PACKET_SIZE) {
			r_ready=1;				//signal cmd processor
			r_state = RX_STATE_DONE;
			UCSRB &=~ (1<<RXCIE);			//stop rec ISR, ready processor needs to turn it back on...
		}
	} // no else here.... it would be an error, drop the char
}

//********************************************************** 
//Set it all up
void serial_init(void) {

        UBRRL=UBRRVAL;  //low byte
        UBRRH=(UBRRVAL>>8) & 0x0F;     //high byte

	// Set data frame format: asynchronous mode,no parity, 1 stop bit, 8 bit size
	UCSRC=(0<<UMSEL)|(0<<UPM1)|(0<<UPM0)|(0<<USBS)|(1<<UCSZ1)|(1<<UCSZ0)|(0<<UCPOL);

	//Enable Receiver and Interrupt on receive complete 
	//UCSRB=(1<<RXEN)|(1<<TXEN)|(1<<RXCIE);		// no xmit for now
	UCSRB=(1<<RXEN)|(1<<RXCIE)|(0<<UCSZ2);

	rcv_int();
}

//********************************************************** 
// initialize ISR-driven receive. This sets up the ISR,
// which then does all the work of getting a command.
void rcv_int(void) {
	r_state = RX_STATE_SYNC;
	r_ready = 0;
	r_index = 0;
	UCSRB |= (1<<RXCIE);		//start rec ISR
}

